<?php
/**
 * Author: dadadezhou <379559090@qq.com>
 * Date: 2022-10-09
 * Time: 15:21
 * Description: 后台首页控制器
 */

defined('ROOT_PATH') or exit;

class index_control extends admin_control{

	// 后台首页
	public function index() {
        $cfg = $this->kv->xget('cfg');

        // hook admin_index_control_index_after.php
        $this->assign('cfg', $cfg);
        $this->display();
	}

	// 后台登录
	public function login() {
		if(empty($_POST)) {
            // hook admin_index_control_login_before.php

			$this->display();
		}elseif(form_submit()) {
            // hook admin_index_control_login_post_before.php

			$user = &$this->user;
			$username = R('username', 'P');
			$password = R('password', 'P');

			if($message = $user->check_username($username)) {
			    E(1, $message);
			}elseif($message = $user->check_password($password)){
                E(1, $message);
			}

            // hook admin_index_control_login_post_check_after.php

			// 防IP暴力破解
			$ip = &$_ENV['_ip'];
			if($user->anti_ip_brute($ip)) {
                E(1, lang('please_try_15_min'));
			}

			$data = $user->get_user_by_username($username);
			if($data && $user->verify_password($password, $data['salt'], $data['password'])) {
                // hook admin_index_control_login_post_success.php

				// 写入 cookie
				$admauth = str_auth("$data[uid]\t$data[username]\t$data[password]\t$data[groupid]", 'ENCODE');
				_setcookie('admauth', $admauth, 0, '', '', false, true);

				// 更新登陆信息
				$data['lastip'] = $data['loginip'];
				$data['lastdate'] = $data['logindate'];
				$data['loginip'] = ip2long($ip);
				$data['logindate'] = $_ENV['_time'];
				$data['logins']++;
				$user->update($data);

				// 删除密码错误记录
				$this->runtime->delete('password_error_'.$ip);

                E(0, lang('login_successfully'));
			}else{
                // hook admin_index_control_login_post_error.php

				// 记录密码错误日志
				$log_password = '******'.substr($password, 6);
				log::write(lang('password_error')."：$username - $log_password", 'login_log.php');

				// 记录密码错误次数
				$user->password_error($ip);

                E(1, lang('username_password_error'));
			}
		}else{
            E(1, lang('form_invalid'));
		}
	}

	// 后台退出登录
	public function logout(){
        if($_POST){
            // hook admin_index_control_logout_before.php
            _setcookie('admauth', '', 1);
            $res = array(
                'code'=>1, 'msg'=>lang('logout_successfully')
            );
            exit( json_encode($res) );
        }else{
            $res = array(
                'code'=>0, 'msg'=>lang('data_error')
            );
            exit( json_encode($res) );
        }
	}

	// hook admin_index_control_after.php
}
